//    Copyright (C) 2013  <lugocreation@gmail.com>
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
package org.jpgolay.me.supplier;

import java.awt.event.*;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.*;
import org.jpgolay.gui.fixed.*;
import org.jpgolay.gui.iconBar.*;
import org.jpgolay.me.family.Family;
import org.jpgolay.me.persistence.ObjectCRUD;
import org.jpgolay.me.util.*;

// Referenced classes of package org.jpgolay.me.supplier:
//            SupplierGUI, SupplierCRUD, SupplierPrint, Supplier
public class SupplierController extends SupplierGUI {

    private class MouseClickList extends MouseAdapter {

        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                actionLoad((String) supplierTable.getTable().getValueAt(supplierTable.getTable().getSelectedRow(), 0));
            }
        }

        MouseClickList() {
        }
    }

    public SupplierController(Parameter param) {
        create = false;
        supplierTable = null;
        write = false;
        this.param = param;
        crud = new ObjectCRUD();
        supplierCrud = new SupplierCRUD();
        initLaw();
        initMenu();
        initIconBar();
        initField();
        initSupplierFamilyList();
        initSearch();
        initTable();
    }

    private void initLaw() {
        if (param.getAccessLaw().length() >= 13 && param.getAccessLaw().charAt(13) == '1') {
            write = true;
        }
    }

    private void initMenu() {
        getMenuPanel().getExit().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionExit();
            }
        });
        getMenuPanel().getDelete().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionRemove();
            }
        });
        getMenuPanel().getHelp().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionHelp();
            }
        });
        getMenuPanel().getModify().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionModify();
            }
        });
        getMenuPanel().getNew().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionNew();
            }
        });
        getMenuPanel().getOpen().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent actionevent) {
            }
        });
        getMenuPanel().getPrint().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionPrint(true);
            }
        });
        getMenuPanel().getSave().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionSave();
            }
        });
    }

    private void initIconBar() {
        getIconBarPanel().addAnswerListener(new AnswerListener() {
            public void create(AnswerEvent e) {
                actionNew();
            }

            public void open(AnswerEvent answerevent) {
            }

            public void modify(AnswerEvent e) {
                actionModify();
            }

            public void save(AnswerEvent e) {
                actionSave();
            }

            public void remove(AnswerEvent e) {
                actionRemove();
            }

            public void print(AnswerEvent e) {
                actionPrint(false);
            }

            public void help(AnswerEvent e) {
                actionHelp();
            }
        });
    }

    private void initField() {
        cleanField();
        setEnabledField(false);
        getIconBarPanel().setEnabledCreate(write);
        getIconBarPanel().setEnabledSave(false);
        getIconBarPanel().setEnabledModify(false);
        getIconBarPanel().setEnabledRemove(false);
        getIconBarPanel().setEnabledPrint(false);
        getIconBarPanel().setEnabledOpen(false);
        getMenuPanel().getNew().setEnabled(write);
        getMenuPanel().getSave().setEnabled(false);
        getMenuPanel().getModify().setEnabled(false);
        getMenuPanel().getDelete().setEnabled(false);
        getMenuPanel().getPrint().setEnabled(false);
        getMenuPanel().getOpen().setEnabled(false);
        create = false;
    }

    private void initSupplierFamilyList() {
        java.util.Collection c = crud.readAll(null, 10);
        if (c != null) {
            Family family = null;
            ArrayList familyList = new ArrayList(c);
            Iterator it = familyList.iterator();
            String list[] = new String[familyList.size()];
            for (int i = 0; it.hasNext(); i++) {
                family = (Family) it.next();
                list[i] = family.getId();
            }

            setFamilyList(list);
        } else {
            setFamilyList(new String[]{
                        "aucune"
                    });
        }
    }

    private void initSearch() {
        getSupplierSearchBox().setList(new String[]{
                    "Code", "Raison social", "Ville", "Famille"
                });
        getSupplierSearchBox().setVal("");
        getSupplierSearchBox().setAdvanceSearch(getSupplierTable());
        getSupplierSearchBox().getButtonRight().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionSearch();
            }
        });
        getSupplierSearchBox().getTextField().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionSearch();
            }
        });
    }

    private void initTable() {
        supplierTable.setTypes(new Class[]{
                    java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
                });
        supplierTable.setLastColumnNotEditable(0);
        supplierTable.setCellEditable(false);
        supplierTable.setAlternateColor(MEUtility.SUPPLIER_LINE);
        supplierTable.setColumnNames(new String[]{
                    "CODE", "FOURNISSEUR", "VILLE", "FAMILLE"
                });
        supplierTable.setPreferredColumnSize(new int[]{
                    40, 50, 40, 50
                });
        actionSearch();
    }

    private TableViewer getSupplierTable() {
        if (supplierTable == null) {
            supplierTable = new TableViewer();
        }
        return supplierTable;
    }

    private void actionExit() {
        setVisible(false);
    }

    private void actionRemove() {
        int reponse = JOptionPane.showConfirmDialog(null, "Etes-vous certain de vouloir suprimer ce Fournisseur ?", "Confirmation", 1, 2, null);
        switch (reponse) {
            case 0: // '\0'
                actionDelete();
            // fall through

            case -1:
            case 1: // '\001'
            case 2: // '\002'
            default:
                return;
        }
    }

    private void actionHelp() {
        BrowserControl.displayURL("www.media-4-u.net");
    }

    private void actionModify() {
        setEnabledField(true);
        getIconBarPanel().setEnabledCreate(false);
        getIconBarPanel().setEnabledSave(true);
        getIconBarPanel().setEnabledModify(false);
        getIconBarPanel().setEnabledRemove(true);
        getMenuPanel().getNew().setEnabled(false);
        getMenuPanel().getSave().setEnabled(true);
        getMenuPanel().getModify().setEnabled(false);
        getMenuPanel().getDelete().setEnabled(true);
    }

    private void actionNew() {
        initField();
        setEnabledField(true);
        getIconBarPanel().setEnabledCreate(false);
        getIconBarPanel().setEnabledSave(true);
        getMenuPanel().getNew().setEnabled(false);
        getMenuPanel().getSave().setEnabled(true);
        create = true;
    }

    private void actionPrint(boolean b) {
        SupplierPrint prt = new SupplierPrint(supplier, getPiecesList(), b, param);
    }

    private void actionSave() {
        if (create) {
            actionCreate();
        } else {
            actionUpdate();
        }
    }

    private Object[][] getPiecesList() {
        Object data[][] = supplierCrud.getDataList("SELECT id, date, recu_le, (net_a_payer - montant_regle), net_a_payer FROM achats WHERE fournisseurs_id='" + supplier.getId() + "'");
        if (data == null) {
            return new Object[1][5];
        } else {
            return data;
        }
    }

    private void actionSearch() {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT id, raison_sociale, ville_com, familles_fournisseurs_id FROM fournisseurs");
        switch (getSupplierSearchBox().getSelectedIndex()) {
            case 0: // '\0'
                if (getSupplierSearchBox().getVal().equals("")) {
                    sql.append(" ORDER BY id");
                } else {
                    sql.append(" WHERE id LIKE '");
                    sql.append(getSupplierSearchBox().getVal());
                    sql.append("%' ORDER BY id");
                }
                break;

            case 1: // '\001'
                if (getSupplierSearchBox().getVal().equals("")) {
                    sql.append(" ORDER BY raison_sociale");
                } else {
                    sql.append(" WHERE raison_sociale LIKE '");
                    sql.append(getSupplierSearchBox().getVal());
                    sql.append("%' ORDER BY raison_sociale");
                }
                break;

            case 2: // '\002'
                if (getSupplierSearchBox().getVal().equals("")) {
                    sql.append(" ORDER BY ville_com");
                } else {
                    sql.append(" WHERE ville_com LIKE '");
                    sql.append(getSupplierSearchBox().getVal());
                    sql.append("%' ORDER BY ville_com");
                }
                break;

            case 3: // '\003'
                if (getSupplierSearchBox().getVal().equals("")) {
                    sql.append(" ORDER BY familles_fournisseurs_id");
                } else {
                    sql.append(" WHERE familles_fournisseurs_id LIKE '");
                    sql.append(getSupplierSearchBox().getVal());
                    sql.append("%' ORDER BY familles_fournisseurs_id");
                }
                break;

            default:
                if (getSupplierSearchBox().getVal().equals("")) {
                    sql.append(" ORDER BY id");
                } else {
                    sql.append(" WHERE id LIKE '");
                    sql.append(getSupplierSearchBox().getVal());
                    sql.append("%' ORDER BY id");
                }
                break;
        }
        Object data[][] = supplierCrud.getDataList(sql.toString());
        if (data != null) {
            supplierTable.setData(data);
            supplierTable.getTable().addMouseListener(new MouseClickList());
        } else {
            supplierTable.setData(getEmptyTable());
        }
    }

    private Object[][] getEmptyTable() {
        Object data[][] = new Object[3][4];
        for (int i = 0; i < data.length; i++) {
            data[i][0] = null;
            if (i == 1) {
                data[i][1] = "AUCUN";
                data[i][2] = "FOURNISSEUR";
            } else {
                data[i][1] = null;
                data[i][2] = null;
            }
            data[i][3] = null;
        }

        return data;
    }

    private void actionLoad(String pk) {
        supplier = (Supplier) crud.read(pk, 9);
        if (supplier != null) {
            initField();
            setCompanyValue(supplier.getRaisonSociale());
            setStatusValue(supplier.getCivilite());
            setSalesAddrLn1Value(supplier.getAdresseComUn());
            setSalesAddrLn2Value(supplier.getAdresseComDeux());
            setSalesCityValue(supplier.getVilleCom());
            setSalesCountryValue(supplier.getPaysCom());
            setSalesZipValue(supplier.getCpCom());
            setContactValue(supplier.getNomPrenomContact());
            setJobContactValue(supplier.getFonctionContact());
            setTelValue(supplier.getTelephone());
            setFaxValue(supplier.getFax());
            setShippingAddrLn1Value(supplier.getAdresseEnlevUn());
            setShippingAddrLn2Value(supplier.getAdresseEnlevDeux());
            setShippingCityValue(supplier.getVilleEnlev());
            setShippingZipValue(supplier.getCpEnlev());
            setShippingCountryValue(supplier.getPaysEnlev());
            setGlnValue(supplier.getGln());
            setEmailValue(supplier.getEmail());
            setWebValue(supplier.getSiteWeb());
            setTel2Value(supplier.getPortable());
            setFamilyValue(supplier.getFamilleFournisseurId());
            setBankNumberValue(supplier.getNumeroCompte());
            setLastUserValue(supplier.getUserId());
            setLastTimeValue(supplier.getUpdateLastTime());
            setIdValue(supplier.getId());
            setNotesValue(supplier.getCommentaire());
            setTitle("FOURNISSEUR (CODE : " + supplier.getId() + ")");
            getIconBarPanel().setEnabledModify(write);
            getIconBarPanel().setEnabledPrint(true);
            getMenuPanel().getModify().setEnabled(write);
            getMenuPanel().getPrint().setEnabled(true);
        }
    }

    private void actionUpdate() {
        if (verifyRequirement()) {
            supplier.setRaisonSociale(getCompanyValue());
            supplier.setCivilite(getStatusValue());
            supplier.setAdresseComUn(getSalesAddrLn1Value());
            supplier.setAdresseComDeux(getSalesAddrLn2Value());
            supplier.setVilleCom(getSalesCityValue());
            supplier.setPaysCom(getSalesCountryValue());
            supplier.setCpCom(getSalesZipValue());
            supplier.setNomPrenomContact(getContactValue());
            supplier.setFonctionContact(getJobContactValue());
            supplier.setTelephone(getTelValue());
            supplier.setFax(getFaxValue());
            supplier.setAdresseEnlevUn(getShippingAddrLn1Value());
            supplier.setAdresseEnlevDeux(getShippingAddrLn2Value());
            supplier.setVilleEnlev(getShippingCityValue());
            supplier.setCpEnlev(getShippingZipValue());
            supplier.setPaysEnlev(getShippingCountryValue());
            supplier.setGln(getGlnValue());
            supplier.setEmail(getEmailValue());
            supplier.setSiteWeb(getWebValue());
            supplier.setPortable(getTel2Value());
            supplier.setFamilleFournisseurId(getFamilyValue());
            supplier.setNumeroCompte(getBankNumberValue());
            supplier.setCommentaire(getNotesValue());
            supplier.setUserId(param.getUserId());
            crud.update(supplier, 9);
            initField();
            initSupplierFamilyList();
        }
    }

    private void actionCreate() {
        if (verifyRequirement()) {
            String pk = (String) crud.create(9, getIdValue());
            if (pk != null) {
                supplier = (Supplier) crud.read(pk, 9);
                supplier.setRaisonSociale(getCompanyValue());
                supplier.setCivilite(getStatusValue());
                supplier.setAdresseComUn(getSalesAddrLn1Value());
                supplier.setAdresseComDeux(getSalesAddrLn2Value());
                supplier.setVilleCom(getSalesCityValue());
                supplier.setPaysCom(getSalesCountryValue());
                supplier.setCpCom(getSalesZipValue());
                supplier.setNomPrenomContact(getContactValue());
                supplier.setFonctionContact(getJobContactValue());
                supplier.setTelephone(getTelValue());
                supplier.setFax(getFaxValue());
                supplier.setAdresseEnlevUn(getShippingAddrLn1Value());
                supplier.setAdresseEnlevDeux(getShippingAddrLn2Value());
                supplier.setVilleEnlev(getShippingCityValue());
                supplier.setCpEnlev(getShippingZipValue());
                supplier.setPaysEnlev(getShippingCountryValue());
                supplier.setGln(getGlnValue());
                supplier.setEmail(getEmailValue());
                supplier.setSiteWeb(getWebValue());
                supplier.setPortable(getTel2Value());
                supplier.setFamilleFournisseurId(getFamilyValue());
                supplier.setNumeroCompte(getBankNumberValue());
                supplier.setCommentaire(getNotesValue());
                supplier.setUserId(param.getUserId());
                crud.update(supplier, 9);
                initField();
                initSupplierFamilyList();
            } else {
                JOptionPane.showMessageDialog(null, "Code Fournisseur refus\351 !\n(v\351rif\351 si ce code n'est pas d\351j\340 utilis\351)");
            }
        }
    }

    private void actionDelete() {
        crud.delete(supplier.getId(), supplier.getUpdateLastTime(), 9);
        initField();
        initSupplierFamilyList();
    }

    private boolean verifyRequirement() {
        if (getNotesValue() != null && getNotesValue().length() > 250) {
            JOptionPane.showMessageDialog(null, "Commentaires trop long (maxi. 250 caract\350res) !");
            return false;
        }
        if (getCompanyValue().length() < 2 || getCompanyValue().length() > 50) {
            JOptionPane.showMessageDialog(null, "Raison sociale obligatoire (mini. 2 caract\350res, maxi. 50 caract\350res) !");
            return false;
        }
        if (getSalesCountryValue() != null && getSalesCountryValue().length() > 50) {
            JOptionPane.showMessageDialog(null, "Adresse commercial Pays trop long (maxi. 50 caract\350res) !");
            return false;
        }
        if (getShippingCountryValue() != null && getShippingCountryValue().length() > 50) {
            JOptionPane.showMessageDialog(null, "Adresse d'enl\350vement Pays trop long (maxi. 50 caract\350res) !");
            return false;
        }
        if (getTel2Value() != null && getTel2Value().length() > 20) {
            JOptionPane.showMessageDialog(null, "T\351l\351phone 2 trop long (maxi. 20 caract\350res) !");
            return false;
        }
        if (getEmailValue() != null && getEmailValue().length() > 100) {
            JOptionPane.showMessageDialog(null, "Email trop long (maxi. 100 caract\350res) !");
            return false;
        }
        if (getFaxValue() != null && getFaxValue().length() > 20) {
            JOptionPane.showMessageDialog(null, "Fax trop long (maxi. 20 caract\350res) !");
            return false;
        }
        if (getTelValue() != null && getTelValue().length() > 20) {
            JOptionPane.showMessageDialog(null, "T\351l\351phone trop long (maxi. 20 caract\350res) !");
            return false;
        }
        if (getSalesZipValue() != null && getSalesZipValue().length() > 20) {
            JOptionPane.showMessageDialog(null, "Adresse commercial Code postal trop long (maxi. 20 caract\350res) !");
            return false;
        }
        if (getSalesCityValue() != null && getSalesCityValue().length() > 50) {
            JOptionPane.showMessageDialog(null, "Adresse commercial Ville trop longue (maxi. 50 caract\350res) !");
            return false;
        }
        if (getSalesAddrLn2Value() != null && getSalesAddrLn2Value().length() > 100) {
            JOptionPane.showMessageDialog(null, "Adresse commercial ligne 2 trop longue (maxi. 100 caract\350res) !");
            return false;
        }
        if (getSalesAddrLn1Value() != null && getSalesAddrLn1Value().length() > 100) {
            JOptionPane.showMessageDialog(null, "Adresse commercial ligne 1 trop longue (maxi. 100 caract\350res) !");
            return false;
        }
        if (getShippingZipValue() != null && getShippingZipValue().length() > 20) {
            JOptionPane.showMessageDialog(null, "Adresse d'enl\350vement Code postal trop long (maxi. 20 caract\350res) !");
            return false;
        }
        if (getShippingCityValue() != null && getShippingCityValue().length() > 50) {
            JOptionPane.showMessageDialog(null, "Adresse d'enl\350vement Ville trop longue (maxi. 50 caract\350res) !");
            return false;
        }
        if (getShippingAddrLn2Value() != null && getShippingAddrLn2Value().length() > 100) {
            JOptionPane.showMessageDialog(null, "Adresse d'enl\350vement ligne 2 trop longue (maxi. 100 caract\350res) !");
            return false;
        }
        if (getShippingAddrLn1Value() != null && getShippingAddrLn1Value().length() > 100) {
            JOptionPane.showMessageDialog(null, "Adresse d'enl\350vement ligne 1 trop longue (maxi. 100 caract\350res) !");
            return false;
        }
        if (getContactValue() != null && getContactValue().length() > 50) {
            JOptionPane.showMessageDialog(null, "Contact trop long (maxi. 50 caract\350res) !");
            return false;
        }
        if (getJobContactValue() != null && getJobContactValue().length() > 50) {
            JOptionPane.showMessageDialog(null, "Fonction contact trop longue (maxi. 50 caract\350res) !");
            return false;
        }
        if (getGlnValue() != null && getGlnValue().length() > 50) {
            JOptionPane.showMessageDialog(null, "GLN trop long (maxi. 50 caract\350res) !");
            return false;
        }
        if (getBankNumberValue() != null && getBankNumberValue().length() > 50) {
            JOptionPane.showMessageDialog(null, "N\260 compte trop long (maxi. 50 caract\350res) !");
            return false;
        }
        if (getWebValue() != null && getWebValue().length() > 100) {
            JOptionPane.showMessageDialog(null, "Site web trop long (maxi. 100 caract\350res) !");
            return false;
        } else {
            return true;
        }
    }
    private ObjectCRUD crud;
    private SupplierCRUD supplierCrud;
    private Parameter param;
    private boolean create;
    private Supplier supplier;
    private TableViewer supplierTable;
    private boolean write;
}
